﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace ODataPQ.Extensions
{
    public class QueryableExtensions
    {
        //private static MethodInfo _limitResultsGenericMethod = typeof(QueryableExtensions).GetMethod("LimitResults");
        private static MethodInfo _getCountGenericMethod = typeof(QueryableExtensions).GetMethod("GetIQueryableCount");
        private static MethodInfo _getPagedResultsGenericMethod = typeof(QueryableExtensions).GetMethod("GetPagedResults");

        //internal static IQueryable LimitResults(IQueryable queryable, int limit, out bool resultsLimited)
        //{
        //    MethodInfo genericMethod = _limitResultsGenericMethod.MakeGenericMethod(queryable.ElementType);
        //    object[] args = new object[] { queryable, limit, null };
        //    IQueryable results = genericMethod.Invoke(null, args) as IQueryable;
        //    resultsLimited = (bool)args[2];
        //    return results;
        //}

        //public static IQueryable<T> LimitResults<T>(IQueryable<T> queryable, int limit, out bool resultsLimited)
        //{
        //    // queryable.Skip(limit).Take()
        //    resultsLimited = true;
        //    return queryable;
        //}

        internal static IQueryable GetPagedResults(IQueryable queryable, int skip, int take)
        {
            MethodInfo genericMethod = _getPagedResultsGenericMethod.MakeGenericMethod(queryable.ElementType);
            object[] args = new object[] { queryable, skip, take };
            IQueryable results = genericMethod.Invoke(null, args) as IQueryable;
            return results;
        }

        public static IQueryable<T> GetPagedResults<T>(IQueryable<T> queryable, int skip, int take)
        {
            return queryable.Skip(skip).Take(take);
        }


        internal static int GetIQueryableCount(IQueryable queryable)
        {
            MethodInfo genericMethod = _getCountGenericMethod.MakeGenericMethod(queryable.ElementType);
            object[] args = new object[] { queryable };
            return (int)genericMethod.Invoke(null, args);
        }

        public static int GetIQueryableCount<T>(IQueryable<T> queryable)
        {
            return queryable.Count();
        }
    }
}